package com.dynabook.ems.utils;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@Slf4j
public class HttpUtil {

    // 定义常量
    private static final int DEFAULT_TIMEOUT = 10000;
    private static final String CONTENT_TYPE_JSON = "application/json";

    /**
     * 发送HTTP请求
     *
     * @param url    请求URL
     * @param body   请求体（JSON对象）
     * @param method 请求方法（GET或POST）
     * @return HTTP响应
     */
    public static HttpResponse sendRequest(String url, JSONObject body, String method) {
        return sendRequest(url, body, method, null);
    }

    /**
     * 发送HTTP请求
     *
     * @param url     请求URL
     * @param body    请求体（JSON对象）
     * @param method  请求方法（GET或POST）
     * @param headers 自定义请求头
     * @return HTTP响应
     */
    public static HttpResponse sendRequest(String url, JSONObject body, String method, Map<String, String> headers) {
        return sendRequest(url, body, method, headers, DEFAULT_TIMEOUT);
    }
    
    /**
     * 发送HTTP请求
     *
     * @param url     请求URL
     * @param body    请求体（JSON对象）
     * @param method  请求方法（GET或POST）
     * @param headers 自定义请求头
     * @param timeout 超时时间（毫秒）
     * @return HTTP响应
     */
    public static HttpResponse sendRequest(String url, JSONObject body, String method, Map<String, String> headers, int timeout) {
        if (url == null || url.isEmpty()) {
            throw new IllegalArgumentException("URL不能为空");
        }
        
        if (method == null || method.isEmpty()) {
            throw new IllegalArgumentException("请求方法不能为空");
        }
        
        HttpResponse response = null;
        try {
            log.info("发起{}请求: URL={}, 参数={}", method, url, body != null ? body.toString() : "无");
            
            if ("POST".equalsIgnoreCase(method)) {
                HttpRequest request = HttpRequest.post(url)
                        .header(Header.CONTENT_TYPE, CONTENT_TYPE_JSON)
                        .header(Header.CONNECTION, "keep-alive")
                        .timeout(timeout);
                
                if (body != null) {
                    request.body(body.toString());
                }

                if (headers != null) {
                    for (Map.Entry<String, String> entry : headers.entrySet()) {
                        request.header(entry.getKey(), entry.getValue());
                    }
                }

                response = request.execute();
            } else if ("GET".equalsIgnoreCase(method)) {
                HttpRequest request = HttpRequest.get(url)
                        .header(Header.CONTENT_TYPE, CONTENT_TYPE_JSON)
                        .timeout(timeout);
                
                // 对于GET请求，如果有body参数，将其作为URL参数附加
                if (body != null && !body.isEmpty()) {
                    for (String key : body.keySet()) {
                        request.form(key, body.get(key));
                    }
                }

                if (headers != null) {
                    for (Map.Entry<String, String> entry : headers.entrySet()) {
                        request.header(entry.getKey(), entry.getValue());
                    }
                }

                response = request.execute();
            } else {
                throw new IllegalArgumentException("不支持的HTTP方法: " + method);
            }
            
            log.info("HTTP请求响应状态码: {}", response.getStatus());
            return response;
        } catch (Exception e) {
            log.error("HTTP请求异常: {}", e.getMessage(), e);
            throw new RuntimeException("HTTP请求失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 发送GET请求
     *
     * @param url 请求URL
     * @return HTTP响应
     */
    public static HttpResponse get(String url) {
        return sendRequest(url, null, "GET");
    }
    
    /**
     * 发送GET请求（带参数）
     *
     * @param url 请求URL
     * @param params 请求参数
     * @return HTTP响应
     */
    public static HttpResponse get(String url, Map<String, Object> params) {
        JSONObject jsonParams = new JSONObject();
        if (params != null) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                jsonParams.set(entry.getKey(), entry.getValue());
            }
        }
        return sendRequest(url, jsonParams, "GET");
    }
    
    /**
     * 发送POST请求
     *
     * @param url 请求URL
     * @param body 请求体
     * @return HTTP响应
     */
    public static HttpResponse post(String url, JSONObject body) {
        return sendRequest(url, body, "POST");
    }
    
    /**
     * 发送POST请求（Map参数自动转JSON）
     *
     * @param url 请求URL
     * @param params 请求参数
     * @return HTTP响应
     */
    public static HttpResponse post(String url, Map<String, Object> params) {
        JSONObject jsonParams = new JSONObject();
        if (params != null) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                jsonParams.set(entry.getKey(), entry.getValue());
            }
        }
        return sendRequest(url, jsonParams, "POST");
    }
    
    /**
     * 解析HTTP响应为JSONObject
     *
     * @param response HTTP响应
     * @return JSONObject
     */
    public static JSONObject parseResponse(HttpResponse response) {
        if (response == null) {
            return null;
        }
        
        String body = response.body();
        if (body == null || body.isEmpty()) {
            return new JSONObject();
        }
        
        try {
            return JSONUtil.parseObj(body);
        } catch (Exception e) {
            log.error("解析响应JSON失败: {}", e.getMessage(), e);
            throw new RuntimeException("解析响应JSON失败: " + e.getMessage(), e);
        }
    }
}
